package com.naicha.wechat.wechat.utils;

import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;

import java.util.Map;

import static org.apache.http.HttpHeaders.USER_AGENT;
/**
 * @author NaiCha
 * @date 2019/4/25 15:22
 * @description TODO
 **/
@Slf4j
public class HttpRequestUtils {

    /**
     * 处理请求
     * @param baseUrl
     * @param apiUrl
     * @param paramMap
     * @param headers
     * @return
     */
    public static String send_post(String baseUrl, String apiUrl, Object paramMap, Map<String, String> headers) {
        if(!StringUtils.isEmpty(baseUrl)){
            try {
                Unirest.setTimeouts(10000L,60000L);
                HttpResponse<String> response = Unirest.post(baseUrl+apiUrl)
                        .headers(headers)
                        .header("Content-Type", "application/json")
                        .body(GsonUtil.toJson(paramMap))
                        .asString();

                log.info("POST请求["+baseUrl+apiUrl+"]，body："+ JSONObject.valueToString(paramMap));
                if(response.getStatus()== HttpStatus.OK.value()){
                    log.info("POST请求["+baseUrl+apiUrl+"]成功，请求结果："+response.getBody());
                    return response.getBody();
                }
            } catch (UnirestException e) {
                log.error("请求异常：",e);
            }
        }
        return null;
    }

    /**
     * 发送get请求
     * @param url
     * @param headers
     * @return
     */
    public static String send_get(String url,Map<String,String> headers) {
        HttpResponse<String> response = null;
        try {
            response = Unirest.get(url)
                    .headers(headers)
                    .header("User-Agent", USER_AGENT)
                    .asString();
        } catch (UnirestException e) {
            e.printStackTrace();
        }
        if(response != null && response.getStatus() == HttpStatus.OK.value()){
            return response.getBody();
        }else{
            return null;
        }
    }

    /**
     * put
     * @param url
     * @param headers
     * @return
     */
    public static String sendPut(String url,Map<String,String> headers){
        HttpResponse<String> response = null;
        try {
            response = Unirest.put(url)
                    .headers(headers)
                    .header("User-Agent", USER_AGENT)
                    .asString();
        } catch (UnirestException e) {
            e.printStackTrace();
        }
        if(response != null && response.getStatus() == HttpStatus.OK.value()){
            return response.getBody();
        }else{
            return null;
        }
    }

}
